package gwtgaetools.client.ui;

import gwtgaetools.client.ItemManager;
import gwtgaetools.client.ui.SmartInlineLabel;
import gwtgaetools.client.ui.SmartInlineTextbox;

import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.user.client.ui.Widget;

public class EditableLabel<M> {

	public int MIN_WIDTH = 20; // PX
	
	public SmartInlineTextbox<M> textbox = new SmartInlineTextbox<M>();
	public SmartInlineLabel<M> label = new SmartInlineLabel<M>();

	public boolean inEditingMode = false;
	
	public EditableLabel() {}
	
	public EditableLabel(ItemManager<M> m) {
		setItem(m);
	}
	
	public EditableLabel(ItemManager<M> m, String s) {
		this(m);
		addTextboxStyle(s);
	}
	
	public void addKDH(KeyDownHandler kdh) {
		textbox.addKeyDownHandler(kdh);
	}
	
	public void setEditingMode(boolean b) {
		if (b) {
			textbox.setWidth(Math.max(label.getOffsetWidth(), MIN_WIDTH) + "px");
//			textbox.getElement().getStyle().setProperty("fontSize", label.getElement().getStyle().getFontSize());
		} else {
			textbox.setText(label.getText());
			label.setWidth(Math.max(label.getOffsetWidth(), MIN_WIDTH) + "px");
		}
		
		inEditingMode = b;
			
	}
	
	public Widget getActiveWidget() {
		if (inEditingMode)
			return textbox;
		else
			return label;
	}

	public String getText() {
		if (inEditingMode)
			return textbox.getText();
		else
			return label.getText();
	}
	
	public void setItem(ItemManager<M> m) {
		m.registerListener(textbox);
		m.registerListener(label);
	}

	public void addTextboxStyle(String s) {
		textbox.addStyleDependentName(s);
		label.addStyleDependentName(s);
	}
	
	public boolean hasNewValue() {
		return !textbox.getText().equals(label.getText());
	}

	public void addClickHandler(ClickHandler clickHandler) {
		label.addClickHandler(clickHandler);
	}
}
